package com.nirvana.utils;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;

import java.util.Arrays;

public class CodeUtil {
    public static Project project;
    public static void findPluginGenerateRange() {
        VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByIoFile(null);
        PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);

        psiFile.getChildren();
    }
    public static void addField() {
        JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
        PsiClass aClass = javaPsiFacade.findClass("", GlobalSearchScope.allScope(project));

        PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
        elementFactory.createImportStatement(aClass);
        elementFactory.createClass("TestDef").add(elementFactory.createField("test", PsiType.getTypeByName("", project, GlobalSearchScope.allScope(project))));

        VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByIoFile(null);
        PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
        PsiDocumentManager.getInstance(project).getDocument(file);
    }

    public static void deleteField() {

    }

    public static void newMethod() {

    }

    public static void deleteMethod() {

    }

    private static String[] getPropertiesFromTuple(String propertyName) {
        String propertiesStr = propertyName.substring(propertyName.indexOf("(") + 1, propertyName.indexOf(")"));
        return Arrays.stream(propertiesStr.split(",")).map(String::trim).toArray(String[]::new);
    }

    public static String getTupleFbName(String propertyName) {
        StringBuilder propertyBuilder = new StringBuilder();
        for (String property : getPropertiesFromTuple(propertyName)) {
            propertyBuilder.append(property);
        }
        return propertyBuilder.toString();
    }

}
